package com.itheima.web.manager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;

@Component
public class AdminManager {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    AdminService adminService;

    //生成验证码图片
    public LineCaptcha getVerification(String uuid) {
        //1.生成验证码图片
        LineCaptcha lineCaptcha = new LineCaptcha(200,100);

        //2.将图片中验证码存入redis中,时效5分钟
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE+uuid,lineCaptcha.getCode(), Duration.ofMinutes(5));

        //3.返回图片
        return lineCaptcha;
    }

    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {
        //1.获取redis中验证码,和用户的验证码进行比较,若不一致抛异常
        String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);

        if (!StrUtil.equalsIgnoreCase(redisCode,verificationCode)) {
            throw new BusinessException("请输入正确的验证码");
        }

        //2.远程调用service查询用户
        Admin admin = adminService.findByUsername(username);
        //3.判断用户是否存在,若不存在抛异常
        if (admin == null) {
            throw new BusinessException("请输入正确的用户名");
        }

        //4.继续判读密码是否一致,若不对抛异常
        if (!StrUtil.equals(SecureUtil.md5(password),admin.getPassword())) {
            throw new BusinessException("请输入正确的密码");
        }

        //5.删除验证码,生成token
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE+uuid);

        //注意:token中不能存放敏感数据
        admin.setPassword(null);
        String token = JwtUtil.createToken(BeanUtil.beanToMap(admin));

        //6.将token作为key,用户json作为value,放入redis中,设置时效1小时
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN+token, JSON.toJSONString(admin),Duration.ofHours(1));

        //7.生成返回值(存放token),返回
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("token",token);
        return ResponseEntity.ok(resultMap);
    }

    public void logout(String token) {
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN+token);
    }
}
